$(function(){
	
	//searchAction();
	
	/**
	 * 添加事件
	 */
	$('#action_datagrid-toolbar #addAction').linkbutton({
		onClick:function(){
			addAction();
		}
	});
	
	/**
	 * 更新事件
	 */
	$('#action_datagrid-toolbar #editAction').linkbutton({
		onClick:function(){
			editAction();
		}
	});
	
	/**
	 * 删除事件
	 */
	$('#action_datagrid-toolbar #deleteAction').linkbutton({
		onClick:function(){
			deleteAction();
		}
	});
});

/**
 * 查询
 */
function searchAction(){
	var treeObj = $.fn.zTree.getZTreeObj("menuTree");
	var nodes = treeObj.getSelectedNodes();
	if(nodes.length == 0)
		return;
	getAction(null,null,nodes[0]);
}

function getAction(event,treeId,treeNode){
	$.ajax({
		type : "GET",
		url : ctx + "/resource/query",
		data :{menuCode:treeNode.code},
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			
			$("#action_datagrid").datagrid({
				border : false,
				fitColumns : true,
				checkbox : true,
				fit : true,
				remoteSort : false,
				rownumbers : true,
				singleSelect : true,
				toolbar : "#action_datagrid-toolbar",
				data : data.content
			});
		}
	});
}

/**
 * 添加
 */
function addAction(){
	var menuTree = $.fn.zTree.getZTreeObj("menuTree");
	var nodes = menuTree.getSelectedNodes();
	if(nodes.length == 0){
		message("请选中菜单节点");
		return;
	}
	/*if(nodes[0].level != '3'){
		message("该节点无法添加子节点");
		return;
	}*/
	$('#dialog').dialog({
	    title: '添加',
	    width: 500,
	    height: 650,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/resource/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#actionform").form('load',{});
	    	findDrawerByParentCode(行为类型, setDrawer);
	    	getByResourceCode(nodes[0].code,setAuthArea);
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
	    		var bool = $("#actionform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	var data = $("#actionform").serializeJson();
            	var pattern = $("#pattern").textbox("getValue");
            	var views = $("#views").textbox("getValue");
            	if(nodes[0].level == '3' && $.trim(pattern).length == 0 && $.trim(views).length == 0 ){
            		message("该节点下模式或视图必选其中一个");
            		return;
            	}
            	data.menuCode = nodes[0].code;
            	$.ajax({
            		type : "POST",
            		url : ctx + "/resource/create",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"添加成功")){
            				return;
            			}
/*            			var resourceTree = $.fn.zTree.getZTreeObj("menuTree");
            			resourceTree.addNodes(nodes[0], data.content);
            			$('#datagrid').datagrid('appendRow',data.content);*/
            			getAction(null, null, nodes[0]);
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 更新
 */
function editAction(){
	var menuTree = $.fn.zTree.getZTreeObj("menuTree");
	var nodes = menuTree.getSelectedNodes();
	if(nodes.length == 0){
		message("请选中菜单节点");
		return;
	}
	/*if(nodes[0].level != '3'){
		message("该节点无法添加子节点");
		return;
	}*/
	var row = undefined;
	row = getSelectedRow("#action_datagrid");
	if(!row){
		return;
	}
	$('#dialog').dialog({
	    title: '更新',
	    width: 500,
	    height: 650,
	    closed: false,
	    cache: false,
	    modal: true,
	    href:ctx + "/web/system/resource/add.jsp",
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#actionform").form('load',row);
	    	findDrawerByParentCode(行为类型, setDrawer);
	    	getByResourceCode(nodes[0].code,setAuthArea);
	    },
	    buttons: [{
            text:'保存',
            iconCls:'icon-ok',
            handler:function(){
            	var bool = $("#actionform").form('enableValidation').form('validate');
            	if(!bool){
            		return;
            	}
            	
            	var data = $("#actionform").serializeJson();
            	var pattern = $("#pattern").textbox("getValue");
            	var views = $("#views").textbox("getValue");
            	if(nodes[0].level == '3' && $.trim(pattern).length == 0 && $.trim(views).length == 0 ){
            		message("该节点下模式或视图必选其中一个");
            		return;
            	}
            	data.id = row.id;
            	data.menuCode = nodes[0].code;
            	$.ajax({
            		type : "POST",
            		url : ctx + "/resource/update",
            		data :data,
            		dataType : "json",
            		success : function(data) {
            			if(!showMsg(data,"修改成功")){
            				return;
            			}
        				
        				/*var resourceTree = $.fn.zTree.getZTreeObj("menuTree");
            			var node = resourceTree.getNodeByParam("id", row.id, null);
            			node.name = data.content.name;
            			resourceTree.updateNode(node);*/
            			
            			var index = $('#action_datagrid').datagrid('getRowIndex',row);
            			
            			$('#action_datagrid').datagrid('updateRow',{
            				index: index,
        					row: data.content
        				});
            			
            			$('#dialog').dialog('close');
            		}
            	});
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 删除
 */
function deleteAction(){
	var row = null;
	row = getSelectedRow("#action_datagrid");
	if(!row){
		return;
	}
	
	$.messager.confirm('提示', '确定要删除吗?', function(bool){
	    if (bool){
	    	$.ajax({
	    		type : "POST",
	    		url : ctx + "/resource/delete",
	    		data :{id : row.id},
	    		dataType : "json",
	    		success : function(data) {
	    			if(!showMsg(data,"删除成功")){
        				return;
        			}
	    			
/*	    			var resourceTree = $.fn.zTree.getZTreeObj("menuTree");
        			var node = resourceTree.getNodeByParam("id", row.id, null);
        			resourceTree.removeNode(node);*/
    				
    				var index = $('#action_datagrid').datagrid('getRowIndex',row);
	    			$("#action_datagrid").datagrid('deleteRow',index);
	    		}
	    	});
	    }
	});
}

/**
 * 设置类型下拉框
 * @param data
 */
function setDrawer(data){
	var value = $('#actionform #drawerCode').combobox('getValue');
	$('#actionform #drawerCode').combobox({ 
		valueField:'code',
        textField:'name',
        data:data,
        panelHeight:'auto',
        required:true,
        missingMessage:'必须填写'
	});
	if($.trim(value).length != 0){
		$('#actionform #drawerCode').combobox('select',value);
	}
}

/**
 * 设置所属功能（功能类型）下拉框
 * @param data
 */
function setAuthArea(data){
	var value = $('#actionform #authAreaCode').combobox('getValue');
	$('#actionform #authAreaCode').combobox({ 
		valueField:'code',
        textField:'name',
        data:data,
        panelHeight:'auto',
        required:true,
        missingMessage:'必须填写'
	});
	if($.trim(value).length != 0){
		$('#actionform #authAreaCode').combobox('select',value);
	}
}

/**
 * 通过资源code获取授权列表
 * @param resourceCode
 */
function getByResourceCode(resourceCode,callback){
	$.ajax({
		type : "POST",
		url : ctx + "/authArea/findByResourceCode",
		data :{resourceCode : resourceCode},
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			
			if(typeof(callback) == 'function'){
        		callback(data.content);
        	}
		}
	});
}